package sync;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

public class ChecksumMD5 {
	
	private static byte[] createChecksum(String filename) throws FileNotFoundException, IOException, Exception {
		
		byte[] buffer = new byte[1024];
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		InputStream in = new FileInputStream(filename);
		int numRead;
		
		int count = 0;
		
		do {
			numRead = in.read(buffer);
			if(numRead > 0) {
				md5.update(buffer, 0, numRead);
				count++;
			}
		} while(numRead != -1 && count<32000);

		in.close();
		return md5.digest();
	}
	
	public static String getChecksum(String filename) throws Exception {
		
		File file = new File(filename);
		byte[] bytesum = createChecksum(filename);
		long bytes = file.length();
		String checksum = "";
		
		
		for(int i=0; i < bytesum.length; i++) {
			checksum += 
				Integer.toString( ( bytesum[i] & 0xff ) + 0x100, 16).substring( 1 );
		}
		
		checksum += Long.toString(bytes);
		
		return checksum;
	}
}
